<template>
  <div class="game"
    :style="{ width: (sceneWidth * gridWidth + 21) + 'px', height: (sceneHeight * gridHeight + 21) + 'px' }">
    <div class="scene">
      <div v-for="_, i in sceneWidth * sceneHeight" :key="i" class="grid">
        <div class="human" v-if="getHuman(i)" @click="showHuman(i)"></div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { createHuman, type SimpleHuman } from '@/things/lifes/humans/human'

const gridWidth = 10 //格子宽度
const gridHeight = 10 //格子高度
const sceneWidth = 200 //场景宽度
const sceneHeight = 200 //场景高度
const humans = ref<{ [index: number]: SimpleHuman }>({}) //存放所有人物实例
const initHumanNum = 100 //初始人数

let times = 0 //时间步数

const getHuman = (index: number) => {
  if (humans.value.hasOwnProperty(index))
    return humans.value[index]
  return null
}

const showHuman = (index: number) => {
  console.info(humans.value[index].getInstance())
}

const createInitHumans = () => {
  for (let i = 0; i < initHumanNum; i++) {
    const { x, y } = createRandomPos()
    humans.value[sceneWidth * y + x] = createHuman(times, x, y)
  }
}

const createRandomPos = () => {
  const x = Math.floor(Math.random() * sceneWidth)
  const y = Math.floor(Math.random() * sceneHeight)
  if (!humans.value.hasOwnProperty(sceneWidth * y + x)) {
    return { x, y }
  }
  return createRandomPos()
}

const init = () => {
  createInitHumans()
}

const loop = () => {
  setInterval(() => {
    const humanList = Object.values(humans.value)
    humanList.forEach(human => {
      if (human.isAlive()) {
        human.action(times, humanList.map(h => h.getInstance()), sceneWidth, sceneHeight)
      }
    })

    humans.value = {}
    humanList.forEach(human => {
      const { x, y } = human.getInstance().getPos()
      humans.value[sceneWidth * y + x] = human
    })

    times++
  }, 200)
}

const start = () => {
  init()
  loop()
}

start()

</script>

<style scoped>
.game {
  border: 10px solid #b2b2b2;
}

.scene {
  display: flex;
  flex-wrap: wrap;
  border-left: 1px solid #888888;
  border-top: 1px solid #888888;
}

.grid {
  width: 10px;
  height: 10px;
  border-right: 1px solid #888888;
  border-bottom: 1px solid #888888;
}

.human {
  background-color: blue;
  width: 100%;
  height: 100%;
}
</style>
